package com.luck.easyfoodbatch.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.adapter.ConfirmCardAdapter;
import com.luck.easyfoodbatch.entity.Note;
import com.luck.easyfoodbatch.entity.OrderM;
import com.luck.easyfoodbatch.entity.UseYdx;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.mvp.cart.ConfirmOrderModel;
import com.luck.easyfoodbatch.mvp.cart.ConfirmOrderPresenter;
import com.luck.easyfoodbatch.mvp.cart.ConfirmOrderView;
import com.luck.easyfoodbatch.mvp.cart.EditOrderAddressModel;
import com.luck.easyfoodbatch.mvp.cart.EditOrderAddressPresenter;
import com.luck.easyfoodbatch.mvp.cart.EditOrderAddressView;
import com.luck.easyfoodbatch.mvp.mine.ChooseVoucherModel;
import com.luck.easyfoodbatch.mvp.mine.ChooseVoucherPresenter;
import com.luck.easyfoodbatch.mvp.mine.ChooseVoucherView;
import com.luck.easyfoodbatch.mvp.model.ChooseVoucherM;
import com.luck.easyfoodbatch.mvp.model.Collect;
import com.luck.easyfoodbatch.mvp.model.MyAddress;
import com.luck.easyfoodbatch.mvp.model.PlaceOrderM;
import com.luck.easyfoodbatch.mvp.order.OrderCancelYdxModel;
import com.luck.easyfoodbatch.mvp.order.OrderCancelYdxPresenter;
import com.luck.easyfoodbatch.mvp.order.OrderCancelYdxView;
import com.luck.easyfoodbatch.mvp.order.OrderUseYdxModel;
import com.luck.easyfoodbatch.mvp.order.OrderUseYdxPresenter;
import com.luck.easyfoodbatch.mvp.order.OrderUseYdxView;
import com.luck.easyfoodbatch.pay.PayResult;
import com.luck.easyfoodbatch.simcpux.Constants;
import com.luck.easyfoodbatch.util.AlipayUtil;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.SharedPreferencesUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.easyrecyclerview.EasyRecyclerView;
import com.luck.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ConfirmCartOrderActivity extends BaseNoSliderActivity implements ChooseVoucherView, EditOrderAddressView, ConfirmOrderView, OrderUseYdxView, OrderCancelYdxView {
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_order_num)
    TextView tv_order_num;

    private RelativeLayout rl_tab1;
    private RelativeLayout rl_tab2;
    private RelativeLayout rl_tab3;

    private RelativeLayout rl_address;
    private LinearLayout ll_address;
    private TextView tv_name;
    private TextView tv_phone;
    private TextView tv_address_details;

    private LinearLayout ll_seller;
    private LinearLayout ll_things;
    private LinearLayout ll_things2;
    private RelativeLayout rl_weixin;
    private RelativeLayout rl_zhifubao;
    private ImageView iv_seller;
    private ImageView icon_apply;
    private ImageView icon_wechat;
    private TextView tv_text;
    @BindView(R.id.recyclerView)
    EasyRecyclerView recyclerView;
    private LayoutInflater inflater;
    private String address_id = "", adid = "";
    private List<PlaceOrderM.DataBean> orders = new ArrayList<>();
    private ConfirmCardAdapter adapter;
    private EditOrderAddressModel editOrderAddressModel;
    private ConfirmOrderModel orderModel;
    private String cids = "", money = "";
    private Gson gson;
    private int pay_type = 2;
    private View inflateFooter;
    private TextView tv_ydx_money;
    private int fPosition = 0, sPosition = 0;// 选择优惠券的下标
    private ChooseVoucherModel voucherModel;
    private TextView tv_sub_money;
    private OrderUseYdxModel useYdxModel;
    private OrderCancelYdxModel cancelYdxModel;
    private static final int SDK_PAY_FLAG = 1;
    private String order_ids = "";
    private String order_id = "";
    private String vid = "";
    private String p_id = "";
    private IWXAPI api;
    private int a = 0;
    private int b = 0;
    private int c = 0;
    private int d = 0;
    private List<Integer> integers = new ArrayList<>();
    private Handler MyHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Bundle bundle = new Bundle();
                        bundle.putInt("type", 0);
                        bundle.putString("status", "");
                        startAct(MyOrderActivity.class, bundle);
                        sendBroadcast("action.app.cart.refresh");
                        finish();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(mContext, "支付结果确认中",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(mContext, "支付失败",
                                    Toast.LENGTH_SHORT).show();
                        }

                        sendBroadcast("action.app.cart.refresh");
                    }
                    break;
                }

            }
        }
    };

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("action.finishApplyActivity")) {
                Bundle bundle = new Bundle();
                bundle.putInt("type", 0);
                bundle.putString("status", "");
                startAct(MyOrderActivity.class, bundle);
                finish();
            } else if (intent.getAction().equals("action.app.refresh.address")) {
                // 删除没一个地址了
                rl_address.setVisibility(View.VISIBLE);
                ll_address.setVisibility(View.GONE);
                tv_name.setText("");
                tv_phone.setText("");
                address_id = "";
                tv_address_details.setText("");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_order_cart, "确认订单", MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        p_id = (String) SharedPreferencesUtil.getData(ConfirmCartOrderActivity.this, HttpUtil.P_ID, "3");
        api = WXAPIFactory.createWXAPI(this, null);
        api.registerApp(Constants.APP_ID);
        gson = new Gson();
        registerReceiver(receiver, "action.finishApplyActivity");
        inflater = LayoutInflater.from(this);
        useYdxModel = new OrderUseYdxPresenter(this, mContext);
        cancelYdxModel = new OrderCancelYdxPresenter(this, mContext);
        orders = (List<PlaceOrderM.DataBean>) getIntent().getSerializableExtra("list");
        cids = getIntent().getStringExtra("cids");
        money = getIntent().getStringExtra("money");
        if (orders == null) {
            orders = new ArrayList<>();
        }

        // 遍历一遍 商品列表

        for (PlaceOrderM.DataBean order : orders) {
            List<PlaceOrderM.DataBean.OrderInfoBean> orders = order.getOrderInfo();
            for (PlaceOrderM.DataBean.OrderInfoBean item : orders) {
                // 1.包邮，满足包邮件数
                // 4.不包邮，不使用运东西
                int is_free_post = 0;
                String free_post = item.getIs_free_post();//（1不包2包）
                if (!Tools.isNull(free_post)) {
                    is_free_post = Integer.parseInt(free_post);
                }
                String ydx = item.getAllow_ydx();// 1不使用运东西 2使用
                int allow_ydx = 0;
                if (!Tools.isNull(ydx)) {
                    allow_ydx = Integer.parseInt(ydx);
                }
                int number = item.getNum();// 购买数量
                if (is_free_post == 1) {
                    // 不包邮
                    if (allow_ydx == 1) {
                        a++; // 不使用运东西
                    } else {
                        b++; // 使用运东西
                    }
                } else {
                    // 包邮
                    String post_num = item.getFree_post_num();
                    int free_post_num = 0;
                    if (!Tools.isNull(post_num)) {
                        free_post_num = Integer.parseInt(post_num);
                    }
                    if (number < free_post_num) {
                        // 如果达到了包邮条件
                        c++;
                    } else {
                        d++;
                    }
                }
            }
        }

        StringBuffer sb = new StringBuffer();
        integers.clear();
        for (PlaceOrderM.DataBean item : orders) {
            sb.append(item.getOrder_id()).append(",");
            String ydx = item.getAllow_ydx();
            int allow_ydx = 0;
            if (!Tools.isNull(ydx)) {
                allow_ydx = Integer.parseInt(ydx);
            }
            if (allow_ydx == 1) {
                // 不使用运运东西
                integers.add(1);
            }
        }

        order_ids = Tools.tempNames(sb.toString());
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(manager);
        adapter = new ConfirmCardAdapter(mContext, orders, onClickCoupon);
        adapter.addHeader(new RecyclerArrayAdapter.ItemView() {
            @Override
            public View onCreateView(ViewGroup parent) {
                View inflate = inflater.inflate(R.layout.confirm_header, null);
                rl_address = (RelativeLayout) inflate.findViewById(R.id.rl_address);
                ll_address = (LinearLayout) inflate.findViewById(R.id.ll_address);
                tv_name = (TextView) inflate.findViewById(R.id.tv_name);
                tv_phone = (TextView) inflate.findViewById(R.id.tv_phone);
                tv_address_details = (TextView) inflate.findViewById(R.id.tv_address_details);
                rl_address.setOnClickListener(new MyOnClick());
                ll_address.setOnClickListener(new MyOnClick());

                User user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
                if (user != null) {
                    User.DefaultAddressBean bean = user.getDefault_address();
                    if (bean != null) {
                        if (bean.getProvince().equals(p_id)) {
                            rl_address.setVisibility(View.GONE);
                            ll_address.setVisibility(View.VISIBLE);
                            tv_name.setText("收货人：" + bean.getUname());
                            tv_phone.setText(bean.getMobile());
                            String street = bean.getStreet();
                            address_id = bean.getAddress_id();
                            tv_address_details.setText("收货地址：" + bean.getAddress_str() + " " + street);
                        }
                    }
                }
                return inflate;
            }

            @Override
            public void onBindView(View headerView) {

            }
        });
        adapter.addFooter(new RecyclerArrayAdapter.ItemView() {
            @Override
            public View onCreateView(ViewGroup parent) {
                inflateFooter = inflater.inflate(R.layout.confirm_footer, null);
                ll_seller = (LinearLayout) inflateFooter.findViewById(R.id.ll_seller);
                ll_things = (LinearLayout) inflateFooter.findViewById(R.id.ll_things);
                ll_things2 = (LinearLayout) inflateFooter.findViewById(R.id.ll_things2);
                rl_weixin = (RelativeLayout) inflateFooter.findViewById(R.id.rl_weixin);
                rl_zhifubao = (RelativeLayout) inflateFooter.findViewById(R.id.rl_zhifubao);
                iv_seller = (ImageView) inflateFooter.findViewById(R.id.iv_seller);
                icon_apply = (ImageView) inflateFooter.findViewById(R.id.icon_apply);
                icon_wechat = (ImageView) inflateFooter.findViewById(R.id.icon_wechat);
                tv_text = (TextView) inflateFooter.findViewById(R.id.tv_text);
                tv_ydx_money = (TextView) inflateFooter.findViewById(R.id.tv_ydx_money);
                tv_sub_money = (TextView) inflateFooter.findViewById(R.id.tv_sub_money);
                rl_tab1 = (RelativeLayout) inflateFooter.findViewById(R.id.rl_tab1);
                rl_tab2 = (RelativeLayout) inflateFooter.findViewById(R.id.rl_tab2);
                rl_tab3 = (RelativeLayout) inflateFooter.findViewById(R.id.rl_tab3);
                rl_tab1.setOnClickListener(new MyOnClick());
                rl_tab2.setOnClickListener(new MyOnClick());
                rl_tab3.setOnClickListener(new MyOnClick());
                ll_seller.setOnClickListener(new MyOnClick());
                ll_things.setOnClickListener(new MyOnClick());
                ll_things2.setOnClickListener(new MyOnClick());
                rl_weixin.setOnClickListener(new MyOnClick());
                rl_zhifubao.setOnClickListener(new MyOnClick());

                if (orders.size() == 1) {
                    // 只有一件商品的时候 判断是否可以选运东西配送
                    PlaceOrderM.DataBean item = orders.get(0);
                    List<PlaceOrderM.DataBean.OrderInfoBean> orderInfo = item.getOrderInfo();
                    PlaceOrderM.DataBean.OrderInfoBean infoBean = orderInfo.get(0);
                    String ydx = infoBean.getAllow_ydx();// 1不使用运东西 2使用
                    int allow_ydx = 0;
                    if (!Tools.isNull(ydx)) {
                        allow_ydx = Integer.parseInt(ydx);
                    }

                    if (allow_ydx == 1) {
                        // 不使用运运东西
                        ll_things.setVisibility(View.GONE);
                        ll_things2.setVisibility(View.VISIBLE);
                        ll_seller.setBackgroundResource(R.drawable.input_ydx);
                        iv_seller.setImageResource(R.mipmap.select_sel_1x);
                    } else {
                        int is_free_post = 0;
                        String free_post = infoBean.getIs_free_post();//（1不包2包）
                        if (!Tools.isNull(free_post)) {
                            is_free_post = Integer.parseInt(free_post);
                        }
                        // 使用运东西  在判断一下满足包邮条件吗
                        int number = infoBean.getNum();// 购买数量
                        String post_num = infoBean.getFree_post_num();
                        int free_post_num = 0;
                        if (!Tools.isNull(post_num)) {
                            free_post_num = Integer.parseInt(post_num);
                        }
                        if (is_free_post == 2) {
                            // 包邮的情况下
                            if (number < free_post_num) {
                                // 如果达到了包邮条件
                                useYdxModel.requestOrderUseYdx(order_ids);
                            } else {
                                // 不使用运运东西
                                ll_things.setVisibility(View.GONE);
                                ll_things2.setVisibility(View.VISIBLE);
                                ll_seller.setBackgroundResource(R.drawable.input_ydx);
                                iv_seller.setImageResource(R.mipmap.select_sel_1x);
                            }
                        } else {
                            useYdxModel.requestOrderUseYdx(order_ids);
                        }
                    }

                } else {
                    if (b == 0 && d == 0) {
                        // 代表全部商品不使用运东西
                        // 1.包邮，满足包邮件数   4.不包邮，不使用运东西
                        ll_things.setVisibility(View.GONE);
                        ll_things2.setVisibility(View.VISIBLE);
                        ll_seller.setBackgroundResource(R.drawable.input_ydx);
                        iv_seller.setImageResource(R.mipmap.select_sel_1x);
                    } else {
                        useYdxModel.requestOrderUseYdx(order_ids);
                    }
                }
                return inflateFooter;
            }

            @Override
            public void onBindView(View headerView) {
            }
        });
        tv_money.setText("￥" + money);
        adapter.addAll(orders);
        recyclerView.setAdapter(adapter);
    }

    /**
     * 选择积分
     */
    public ConfirmCardAdapter.OnClickCoupon onClickCoupon = new ConfirmCardAdapter.OnClickCoupon() {
        @Override
        public void onCoupon(int index, int position, String orderId) {
            fPosition = index;
            sPosition = position;
            order_id = orderId;
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            intent.setClass(mContext, MyCouponActivity.class);
            bundle.putString("order_id", order_id);
            bundle.putInt("type", 1);
            intent.putExtras(bundle);
            startActivityForResult(intent, 300);
        }
    };

    /**
     * 头尾部点击事件
     */
    public class MyOnClick implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            switch (view.getId()) {
                case R.id.rl_address:
                    intent.setClass(mContext, AddressManagementActivity.class);
                    bundle.putInt("type", 2);
                    bundle.putInt("address_type", 1);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 200);
                    break;
                case R.id.ll_address:
                    intent.setClass(mContext, AddressManagementActivity.class);
                    bundle.putInt("type", 2);
                    bundle.putInt("address_type", 1);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 200);
                    break;

                case R.id.ll_things:
                    break;
                case R.id.ll_things2:
                    if (orders.size() == 1) {
                        // 只有一件商品的时候 判断是否可以选运东西配送
                        PlaceOrderM.DataBean item = orders.get(0);
                        List<PlaceOrderM.DataBean.OrderInfoBean> orderInfo = item.getOrderInfo();
                        PlaceOrderM.DataBean.OrderInfoBean infoBean = orderInfo.get(0);
                        String ydx = infoBean.getAllow_ydx();// 1不使用运东西 2使用
                        int allow_ydx = 0;
                        if (!Tools.isNull(ydx)) {
                            allow_ydx = Integer.parseInt(ydx);
                        }
                        if (allow_ydx == 1) {
                            T.showToast(mContext, "该订单不能使用运东西~");
                        } else {
                            // 使用运东西  在判断一下满足包邮条件吗
                            int is_free_post = 0;
                            String free_post = infoBean.getIs_free_post();//（1不包2包）
                            if (!Tools.isNull(free_post)) {
                                is_free_post = Integer.parseInt(free_post);
                            }
                            int number = infoBean.getNum();// 购买数量
                            String post_num = infoBean.getFree_post_num();
                            int free_post_num = 0;
                            if (!Tools.isNull(post_num)) {
                                free_post_num = Integer.parseInt(post_num);
                            }
                            if (is_free_post == 2) {
                                if (number < free_post_num) {
                                    useYdxModel.requestOrderUseYdx(order_ids);
                                    ll_things.setVisibility(View.VISIBLE);
                                    ll_things2.setVisibility(View.GONE);
                                    iv_seller.setImageResource(R.mipmap.select_def_1x);
                                    ll_seller.setBackgroundResource(R.drawable.input_search);
                                } else {
                                    // 不使用运运东西
                                    T.showToast(mContext, "该订单不能使用运东西~");
                                }
                            } else {
                                useYdxModel.requestOrderUseYdx(order_ids);
                                ll_things.setVisibility(View.VISIBLE);
                                ll_things2.setVisibility(View.GONE);
                                iv_seller.setImageResource(R.mipmap.select_def_1x);
                                ll_seller.setBackgroundResource(R.drawable.input_search);
                            }
                        }

                    } else {
                        if (b == 0 && d == 0) {
                            T.showToast(mContext, "该订单不能使用运东西~");
                        } else {
                            showProgressDialog(getString(R.string.app_loading));
                            useYdxModel.requestOrderUseYdx(order_ids);
                            ll_things.setVisibility(View.VISIBLE);
                            ll_things2.setVisibility(View.GONE);
                            iv_seller.setImageResource(R.mipmap.select_def_1x);
                            ll_seller.setBackgroundResource(R.drawable.input_search);
                        }
                    }
                    break;
                case R.id.ll_seller:
                    // 联系卖家
                    showProgressDialog(getString(R.string.app_loading));
                    cancelYdxModel.orderCancelYdx(order_ids);
                    ll_things.setVisibility(View.GONE);
                    ll_things2.setVisibility(View.VISIBLE);
                    iv_seller.setImageResource(R.mipmap.select_sel_1x);
                    ll_seller.setBackgroundResource(R.drawable.input_ydx);
                    break;
                case R.id.rl_weixin:
                    pay_type = 2;
                    icon_wechat.setImageResource(R.mipmap.select_sel_1x);
                    icon_apply.setImageResource(R.mipmap.select_def_1x);
                    break;
                case R.id.rl_zhifubao:
                    pay_type = 1;
                    icon_wechat.setImageResource(R.mipmap.select_def_1x);
                    icon_apply.setImageResource(R.mipmap.select_sel_1x);
                    break;
                case R.id.rl_tab1:
                    bundle.putInt("flag", 1);
                    startAct(BaseYdxHttpActivity.class, bundle);
                    break;
                case R.id.rl_tab2:
                    bundle.putInt("flag", 2);
                    startAct(BaseYdxHttpActivity.class, bundle);
                    break;
                case R.id.rl_tab3:
                    bundle.putInt("flag", 3);
                    startAct(BaseYdxHttpActivity.class, bundle);
                    break;
            }
        }
    }

    @Override
    public void backClick() {
        Intent intent = new Intent();
        intent.putExtra("order_ids", order_ids);
        setResult(RESULT_OK, intent);
        finish();
        super.backClick();
    }

    @OnClick({ R.id.tv_next})
    public void onClick(View view) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.tv_next:
                if (Tools.isNull(address_id)) {
                    intent.setClass(mContext, AddressManagementActivity.class);
                    bundle.putInt("type", 2);
                    bundle.putInt("address_type", 1);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 200);
                    return;
                }

                List<Note> notes = new ArrayList<>();

                List<PlaceOrderM.DataBean> list = adapter.getList();
                for (PlaceOrderM.DataBean item : list) {
                    List<PlaceOrderM.DataBean.OrderInfoBean> orderInfo = item.getOrderInfo();
                    for (PlaceOrderM.DataBean.OrderInfoBean info : orderInfo) {
                        Note note = new Note();
                        if (!Tools.isNull(info.getNote())) {
                            note.setNote(info.getNote());
                        } else {
                            note.setNote("");
                        }
                        note.setOrder_id(info.getOrder_id() + "");
                        notes.add(note);
                    }
                }
                String note_json = gson.toJson(notes);
                showProgressDialog(getString(R.string.app_loading));
                orderModel = new ConfirmOrderPresenter(this, mContext);
                orderModel.requestConfirmOrder(cids, order_ids, note_json, "2", pay_type + "");
                break;
        }
    }


    public void editOrderAddressSuccess(Collect model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                if(ll_things.getVisibility()==View.VISIBLE) {
                    useYdxModel.requestOrderUseYdx(order_id);
                }else {
                    cancelYdxModel.orderCancelYdx(order_id);
                }
            } else {
                if(ll_things.getVisibility()==View.VISIBLE) {
                    useYdxModel.requestOrderUseYdx(order_id);
                }else {
                    cancelYdxModel.orderCancelYdx(order_id);
                }
                // 如果修改失败 返回上次地址
                useYdxModel.requestOrderUseYdx(order_id);
                T.showToast(mContext, model.getMsg());
            }
        }
    }


    @Override
    public void confirmOrderSuccess(OrderM model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                // 确认订单成功，刷新购物车
                OrderM.DataBean bean = model.getData();
                String params = bean.getParams();
                double price = 0.0;
                if (!Tools.isNull(money)) {
                    price = Double.parseDouble(money);
                }
                switch (pay_type) {
                    case 1:
                        new AlipayUtil(ConfirmCartOrderActivity.this, params, MyHandler);
                        break;
                    case 2:
                        wechatApply(bean);
                        break;
                }
                sendBroadcast("action.app.cart.refresh");
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }

    }

    /**
     * 微信支付
     *
     * @param bean
     */
    private void wechatApply(OrderM.DataBean bean) {
        try {
            PayReq req = new PayReq();
            req.appId = bean.getAppid();
            req.partnerId = bean.getPartnerid();
            req.prepayId = bean.getPrepayid();
            req.nonceStr = bean.getNoncestr();
            req.timeStamp = bean.getTimestamp() + "";
            req.packageValue = bean.getPackageX();
            req.sign = bean.getSign();
            Toast.makeText(this, "正在发起微信支付，请稍候...", Toast.LENGTH_SHORT).show();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            api.registerApp(Constants.APP_ID);
            api.sendReq(req);
        } catch (Exception e) {
            Log.e("PAY_GET", "异常：" + e.getMessage());
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    @Override
    public void orderCancelYdxSuccess(UseYdx model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                UseYdx.DataBean data = model.getData();
                tv_ydx_money.setText("￥" + data.getTotalPostAmount());
                int totalPrivilegeAmount = data.getTotalPrivilegeAmount();
                tv_sub_money.setText("(可减" + totalPrivilegeAmount + "元)");
                double pay_price = data.getTotal_pay_price();
                tv_money.setText("￥" + pay_price);
                tv_order_num.setText("共0件包含运费");
            }
        }
    }

    @Override
    public void orderUseYdxSuccess(UseYdx model) {
        if(ll_address.getVisibility()==View.GONE){

        }else {
            if (model != null) {
                if (model.getStatus() == HttpUtil.RESULT_OK) {
                    UseYdx.DataBean data = model.getData();
                    if (tv_ydx_money != null) {
                        tv_ydx_money.setText("￥" + data.getTotalPostAmount());
                    }
                    int totalPrivilegeAmount = data.getTotalPrivilegeAmount();
                    if (tv_sub_money != null) {
                        tv_sub_money.setText("(可减" + totalPrivilegeAmount + "元)");
                    }
                    double pay_price = data.getTotal_pay_price();
                    tv_money.setText("￥" + pay_price);
                    if (integers.size() == 0) {
                        tv_order_num.setText("共" + orders.size() + "件包含运费");
                    } else {
                        tv_order_num.setText("只包含部分运费");
                    }
                }
            }
        }
    }

    @Override
    public void chooseVoucherSuccess(ChooseVoucherM model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                ChooseVoucherM.DataBean data = model.getData();
                tv_money.setText("￥" + data.getTotal_pay_price());
            }
        }
    }

    @Override
    public void httpStatusError() {
    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 200:
                    if (data != null) {
                        MyAddress.DataBean bean = (MyAddress.DataBean) data.getSerializableExtra("bean");
                        if (bean != null) {
                            rl_address.setVisibility(View.GONE);
                            ll_address.setVisibility(View.VISIBLE);
                            tv_name.setText("收货人：" + bean.getUname());
                            tv_phone.setText(bean.getMobile());
                            String street = bean.getStreet();
                            adid = address_id;
                            address_id = bean.getAddress_id();
                            tv_address_details.setText("收货地址：" + bean.getAddress_str() + " " + street);
                            showProgressDialog(getString(R.string.app_loading));
                            editOrderAddressModel = new EditOrderAddressPresenter(ConfirmCartOrderActivity.this, mContext);
                            editOrderAddressModel.requestEditOrderAddress(order_ids, address_id);
                        }
                    }
                    break;
                case 300:
                    if (data != null) {
                        voucherModel = new ChooseVoucherPresenter(ConfirmCartOrderActivity.this, mContext);
                        String dec_money = data.getStringExtra("money");
                        PlaceOrderM.DataBean dataBean = orders.get(fPosition);
                        List<PlaceOrderM.DataBean.OrderInfoBean> orderInfo = dataBean.getOrderInfo();
                        PlaceOrderM.DataBean.OrderInfoBean infoBean = orderInfo.get(sPosition);
                        if (!Tools.isNull(dec_money)) {
                            vid = data.getStringExtra("vid");
                            infoBean.setYhj(dec_money);
                        } else {
                            infoBean.setYhj("");
                            // 不使用优惠券
                            vid = 0 + "";
                        }
                        adapter.notifyDataSetChanged();
                        voucherModel.requestChooseVoucher(order_id, vid, order_ids);
                    }
                    break;
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                Intent intent = new Intent();
                intent.putExtra("order_ids", order_ids);
                setResult(RESULT_OK, intent);
                finish();
                return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
